<?php
    /**
     * @author plusman < plusmancn@gamil.com >
     * @abstract 微信高级接口发送类
     */
    class Wxapi_hi_int{
        
    	//public $access_token = '';
    	
        public function __construct(){
            //微信参数
            //$where = array(
            //    'id'=>1,
           // );
            //$info = $this->myQueryOne('info',$where);
           // $this->access_token = $info['access_token'];
           $this->CI =& get_instance();
        }

        
        /**
         * @access 对外公开，网络访问 发送消息
         * @param string $touser
         * @param array $articles_body
         * @return Ambigous <string, mixed>
         */
        public function custom_send($touser,$articles_body){
        	
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s",$this->access_token);

            $main_body = array(
                "touser" => $touser,
                "msgtype" => "news",
                "news" => array(
                    'articles' => $articles_body,
                ),
            );

            $data = $this->json_encode_zhcn($main_body);

            $we_response = $this->https_post($url,$data);

            return $we_response;
        }


        
        /**
         * @access 对外公开，网络访问 模板消息 touser(用户openid)
         * @abstract 高级接口，群发函数
         * @param link_url  点击跳转地址
         * @param data  模板设置
         * @param template_id  派单模板
         */
        public function mass_send_by_openid($touser,$link_url,$token,$data,$template_id){
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s",$token);

            $main_body = array(
                "touser" => $touser,
                "template_id" => $template_id,
                "url" => $link_url,
                "data" => $data,
            );

            $data = json_encode($main_body);

            $we_response = $this->https_post($url,$data);

            return $we_response;
        }

		  
        /**
         * @access 对外公开，网络访问  
         * @abstract 高级接口，群发函数  模板信息
         * @param array $touser
         * @param array $articles
         * @return Ambigous <string, mixed>
         */
        public function mass_send_by_groupid($group_ids = array(0),$articles){
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=%s",$this->access_token);
            $media_id = $this->media_uploadnews($articles);
            //foreach ($group_ids as $key => $value) {
                $main_body = array(
                    "filter" => array(
                          "is_to_all"=> true,
                        'group_id' => 0,
                    ),
                    "mpnews" => array(
                        "media_id" => $media_id,
                    ),
                    "msgtype" => "mpnews",
                );
                $data = json_encode($main_body);
               
                $we_response = $this->https_post($url,$data);
           // }

            return $we_response;
        }


        /**
         * @access 对外公开，网络访问
         * @abstract 获取用户分组
         * @param $access_token 账户 openid
         * @author plusman < plusmancn@gmail.com >
         * @since 2014-09-16 13:48:07
         */
        public function get_group(){
            $url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=%s";

            $res = file_get_contents(sprintf($url,$this->access_token));

            return json_decode($res,TRUE);
        }
        
	
        /********************内部函数***************************/
        
        /**
         * @abstract 参数合并
         * @param array $default
         * @param array $options
         * @return array
         */
        function merge_options($default,$options){
            foreach ($default as $key => $value) {
                $key_lower = strtolower($key);
                if(isset($options[$key_lower])){
                    $default[$key] = $options[$key_lower];
                }
            }

            return $default;
        }        

        
        /**
         * @abstract 发送中文消息，中文消息编码
         * @param mixed $data
         * @return string
         */
        function json_encode_zhcn($data){
            return preg_replace('/\\\u([0-9a-f]{4})/ie', "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", json_encode($data));
        }



        /**
         * @abstract 上传图片
         * @param string $pic
         * @return mixed|boolean
         */
        public function upload_image($pic){
            $res = $this->getImage($pic);
            if(!$res['error']){
                $we_response = $this->media_upload($res['save_path']);
                // 返回判断
                if(isset($we_response['media_id'])){
                    return $we_response['media_id'];
                }
            }
            return false;
        }


        
        /**
         * @abstract 上传图文消息
         * @param array $articles
         * @return Ambigous <>|boolean
         */
        public function media_uploadnews($articles){
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=%s",$this->access_token);

            foreach ($articles as $key => $value) {
                $value['thumb_media_id'] = $this->upload_image($value['picurl']);
                unset($value['picurl']);
                $articles_body[$key] = $value;
            }
        

            $main_body = array(
                "articles" => $articles_body,
            );


            $data = $this->json_encode_zhcn($main_body);

            $we_response = $this->https_post($url,$data);

            if(isset($we_response['media_id'])){
                return $we_response['media_id'];
            }else{
                return false;
            }

        }


        
        /**
         * @abstract 下载多媒体资料
         * @param string $media_id
         */
        public function media_download($media_id){
            // Api 地址
            $url = sprintf("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s",$this->access_token,$media_id);

            echo "<a href='".$url."'>Click to download the file</a>";
        }


        
        /**
         * @abstract 上传多媒体资料
         * @param string $path
         * @param string $type
         * @return mixed
         */
        public function media_upload($path,$type="image"){
            // Api 地址
            $url = sprintf("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s",$this->access_token,$type);            
            //模拟POST上传文件  
            $post=array('filename' => '@'.$path);  //POST提交内容   
            $ch = curl_init();  
            curl_setopt($ch, CURLOPT_URL, $url);//URL  
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
            curl_setopt($ch, CURLOPT_POST, 1);  //模拟POST  
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);//POST内容  
            $result = curl_exec($ch);
            curl_close($ch);  

            return json_decode($result,TRUE);
        }

        
        /**
         * @abstract 发送https请求
         * @param string $url
         * @param string|json $data
         * @return array
         */
        public function https_post($url,$data){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($curl);

            if(curl_errno($curl)){
                return 'Errono'.curl_error($curl);
            }

            curl_close($curl);

            return json_decode($result,TRUE);
        }


        
        /**
         * @abstract 发送http请求
         * @param string $url
         * @param string $data
         * @return string|mixed
         */
        public function http_post($url,$data){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($curl);

            if(curl_errno($curl)){
                return 'Errono'.curl_error($curl);
            }

            curl_close($curl);

            return json_decode($result,TRUE);
        }


        
        /**
         * @abstract php实现下载远程图片保存到本地,当保存文件名称为空时则使用远程文件原来的名称
         * @param string $url
         * @param string $save_dir
         * @param string $filename
         * @param number $type
         * @return multitype:string number 
         */
        public function getImage($url,$save_dir='/tmp',$filename='',$type=0){
            if(trim($url)==''){
            return array('file_name'=>'','save_path'=>'','error'=>1);
            }
            if(trim($save_dir)==''){
                $save_dir='./';
            }
            if(trim($filename)==''){//保存文件名
                $ext=strrchr($url,'.');
                if($ext!='.gif'&&$ext!='.jpg'&&$ext!='.png'&&$ext!='.jpeg'){
                    return array('file_name'=>'','save_path'=>'','error'=>3);
                }
                $filename=md5(time().mt_rand(1,10000)).$ext;
            }
            if(0 ==strrpos($save_dir,'/')){
                $save_dir.='/';
            }
            //创建保存目录
            if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
                return array('file_name'=>'','save_path'=>'','error'=>5);
            }
            //获取远程文件所采用的方法 
            if($type){
                $ch=curl_init();
                $timeout=5;
                curl_setopt($ch,CURLOPT_URL,$url);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
                $img=curl_exec($ch);
                curl_close($ch);
            }else{
                ob_start(); 
                readfile($url);
                $img=ob_get_contents(); 
                ob_end_clean(); 
            }
            //$size=strlen($img);
            //文件大小 
            $fp2=@fopen($save_dir.$filename,'a');
            fwrite($fp2,$img);
            fclose($fp2);
            unset($img,$url);
            return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
        }


        /**
         * @abstract 插入 or 更新用户数据
         * @since 2014-09-02 13:09:47
         */
        public function edit_user($_post=''){
            $where = array(
                'gh_num' => $_SESSION['api']['real_gh_num'],
                'openid' => $_post['openid'],
            );

            $_post['hi_gh_num'] = $_SESSION['api']['GH_NUM'];
            $_post['gh_num'] = $_SESSION['api']['real_gh_num'];
            $_post['openid'] = md5($where['gh_num'].$where['openid']);
            $_post['hi_openid'] = $where['openid'];

            unset($_post['privilege']);

            $res = $this->get_detail_info_by_openid($where['gh_num'],$where['openid']);

            if(count($res)){
                $this->CI->db->where($where)->update('user_normal',$_post);
            }else{
                $home_res = $this->CI->db->get_where('user_admin',array('gh_num' => $where['gh_num'],'role_type' => 1))->row_array();
                $_post['ihome_id'] = $home_res['id'];
                $this->CI->db->insert('user_normal',$_post);
            }
            return TRUE;
        }
        
        /**
         * @abstract 获取用户详细信息
         * @param string $openid
         * @return array
         */
        public function get_detail_info_by_openid($gh_num,$openid){
            return $this->CI->db->get_where('user_normal',array('gh_num' => $gh_num ,'hi_openid'=>$openid))->row_array();
        }
        
        
        /**
         * @abstract 公众号创建菜单高级接口
         * @param 公众号 string $gh_num
         * @param 菜单 array $menu
         */
        public function create_menu($menu) {   
            $menu = $this->json_encode_zhcn($menu);
        	$url = sprintf("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s",$this->access_token);
        	return $this->https_post($url, $menu);
        }

        
        /**
         * @abstract 公众号查询菜单高级接口
         * @param 公众号 string $gh_num
         * @return jsonString $menu
         */
        public function query_menu() {   
            //API地址
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s",$this->access_token);
            //返回菜单
            return  file_get_contents($url);
        }


        /**************** 用户分组管理 ***************************/
        /**
         * @abstract 用户分组创建
         */
        function create_group($name){
            // API 地址
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/groups/create?access_token=%s",$this->access_token);

            $post = array(
                "group" => array(
                    "name" => $name,
                ),  
            );

            $we_response = $this->https_post($url,$this->json_encode_zhcn($post));

            return $we_response;
        }

        /**
         * @abstract  移动用户分组
         */
        function update_group($openid,$to_groupid){
            // API 地址
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=%s",$this->access_token);

            $post = array(
                "openid" => $openid,
                "to_groupid" => $to_groupid,
            );

            $we_response = $this->https_post($url,$this->json_encode_zhcn($post));

            return $we_response;

        }
        
        /**
         * @abstract 查询用户所在分组
         */
        function query_group($openid){
            // API 地址
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=%s",$this->access_token);

            $post = array(
                "openid" => $openid,
            );

            $we_response = $this->https_post($url,$this->json_encode_zhcn($post));

            return $we_response;
        }
        /****************** 用户分组 END ************************/
        
    }
?>
